package com.mvc.security.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.mvc.framework.model.Auditable;
import com.mvc.framework.service.BaseService;
import com.mvc.security.model.Role;
import com.mvc.security.model.User;
import com.mvc.security.model.UserRole;

@Service
public class RoleManager extends BaseService<Role, Integer> {

	public List<Role> getAll() {
		Role role = new Role();
		role.setRecStatus(Auditable.REC_STATUS_VALID);
		return getHibernateTemplate().findByExample(role);
	}

	public Role getRoleByName(String name) {
		Role example = new Role();
		example.setName(name);
		List<Role> list = getHibernateTemplate().findByExample(example);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public List<Role> getRolesByUserId(Integer userId) {
		String sql = "SELECT A FROM " + Role.class.getName() + " A, " + UserRole.class.getName()
		        + " B where A.recStatus = " + Auditable.REC_STATUS_VALID + " AND B.recStatus = "
		        + Auditable.REC_STATUS_VALID + " AND A.objectId = B.roleId AND B.userId = " + userId;
		return getHibernateTemplate().find(sql);
	}

	public Role checkIfExistsRole(Role role) {
		String sql = "select A from " + Role.class.getName() + " A where A.recStatus = ? and A.name = ?";
		Object[] parameters = new Object[] { Auditable.REC_STATUS_VALID, role.getName() };
		Integer objectId = role.getObjectId();
		if (objectId != null && objectId != 0) {
			sql += " and A.objectId != ?";
			parameters = new Object[] { Auditable.REC_STATUS_VALID, role.getName(), objectId };
		}
		List<Role> roleList = searchBySql(sql, parameters);
		if (roleList.size() > 0) {
			return roleList.get(0);
		}
		return null;
	}

}
